package com.shortLinked.project.service.impl;

import com.shortLinked.project.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

import static com.shortLinked.project.common.constant.ColoredOutput.RED;
import static com.shortLinked.project.common.constant.ColoredOutput.RESET;

/**
 * url 获取标题接口实现层
 */
@Service
public class UrlTitleServiceImpl implements UrlTitleService {

    @SneakyThrows
    @Override
    public String getTitleByUrl(String url) {
        //https://www.zhihu.com/question/394958149/answer/1896585577668793773
        //传入一个输入进来的链接
        System.out.println(RED+"这里是:getTitleByUrl"+RESET);
        URL targetUrl = new URL(url);
        //对url进行解析
        HttpURLConnection urlConnection = (HttpURLConnection) targetUrl.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            Document document = Jsoup.connect(url).get();
            return document.title();
            //返回一个标题
        }
        return "Error while fatching title!";
    }
}
